package ExecuteEngine;

import java.util.*;
import Const.Constant;
import Const.RC;
import parse.*;

public class Project extends Operation{
	public Attribute_list attr_list;
	public Operation op;
	public Tuple tuple;
	public List<String> titles;
	public String table_newname = null;
	
	public Project(Attribute_list a, Operation o, String t){
		this.attr_list = a;
		this.op = o;
		this.titles = new ArrayList<String>();
		this.type = Operation.PROJECT;
		this.table_newname = t;
	}
	
	public Project(Attribute_list a, Operation o){
		this.attr_list = a;
		this.op = o;
		this.titles = new ArrayList<String>();
		this.type = Operation.PROJECT;
	}
	
	public RC.rc Open(){
		RC.rc re = op.Open();
		
		if(re == RC.rc.SUCCESS){
			StringBuffer star = new StringBuffer("*");
			star.setLength(Constant.MAXNAME);
			if(attr_list.attributes.get(0).GetAttr_Name().equals(star.toString()))
				titles = op.GetTitles();
			else{
				for(int i=0; i<attr_list.attributes.size(); i++){
					String attr = attr_list.attributes.get(i).GetAttr_Name();
					String attr_newname = attr_list.attributes.get(i).attr_newname;
					if(attr_newname == null)
						titles.add(Tuple.Trim(attr));
					else
						titles.add(Tuple.Trim(attr_newname));
				}
			}
				
		}
		
		return re;
	}
	
	public boolean hasNext(){
		return this.op.hasNext();
	}
	
	public Tuple GetNext()
	{
		Tuple src = op.GetNext();
		tuple = new Tuple();
		
		StringBuffer star = new StringBuffer("*");
		star.setLength(Constant.MAXNAME);
		if(attr_list.attributes.get(0).GetAttr_Name().equals(star.toString())){
			if(table_newname != null){
				for(int i=0; i<src.tuple.size(); i++)
					src.tuple.get(i).relName = table_newname;
			}
			return src;
		}
		
		for(int i=0; i<attr_list.attributes.size(); i++){
			StringBuffer s = new StringBuffer(attr_list.attributes.get(i).GetAttr_Name());
			s.setLength(Constant.MAXNAME);
			attr_list.attributes.get(i).SetAttrName(s.toString());
		}
		
		for(int i=0; i<src.tuple.size(); i++){
			if(table_newname != null)
				src.tuple.get(i).relName = table_newname;
			
			String s = src.tuple.get(i).attrName;
			
			for(int j=0; j<attr_list.attributes.size(); j++){
				if(attr_list.attributes.get(j).GetAttr_Name().equals(s)){
					if(attr_list.attributes.get(j).attr_newname != null)
					src.tuple.get(i).attrName = attr_list.attributes.get(j).attr_newname;
					tuple.addElement(src.tuple.get(i));
					break;
				}
			}
		}
		
		return tuple;
	}
	
	public void Close(){
		op.Close();
	}
	
	public List<String> GetTitles(){
		return titles;
	}
}
